export default {
    data() {
        return {
            pager: {
                params: {},
                pagination: {
                    page: 1,
                    size: 20,
                    total: 0
                },
                list: [],
                loading: false,
                finished: false
            }
        };
    },

    computed: {
        Loading() {
            return this.pager.loading;
        },

        Finished() {
            return this.pager.finished;
        },

        Loadmore() {
            return this.pager.list.length;
        },

        List() {
            return this.pager.list;
        },

        EmptyStatus() {
            return !this.Loading && this.Loadmore === 0;
        }
    },

    onReachBottom() {
        if (!this.finish) {
            this.refresh({
                page: this.pager.pagination.page + 1
            });
        }
    },

    async onPullDownRefresh() {
        await this.refresh({ page: 1 });
        uni.stopPullDownRefresh();
    },

    methods: {
        _refresh(params = {}) {
            Object.assign(this.pager.params, params);

            let data = {
                ...this.pager.pagination,
                total: undefined,
                ...this.pager.params
            };

            if (data.page == 1) {
                this.pager.list = [];
                uni.showLoading();
            }

            this.loading = true;

            return {
                data,
                next: p => {
                    return p
                        .then(res => {
                            if (data.page == 1) {
                                this.pager.list = res.list;
                            } else {
                                this.pager.list.push(...res.list);
                            }

                            this.pager.finished = this.pager.list.length === res.pagination.total;
                            this.pager.pagination = res.pagination;

                            uni.hideLoading();
                            this.loading = false;

                            return res;
                        })
                        .catch(err => {
                            uni.showToast({
                                title: err.message,
                                icon: 'none'
                            });

                            uni.hideLoading();
                            this.loading = false;
                        });
                }
            };
        }
    }
};
